package com.kgc.sbt.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created on 2021/7/23.
 * <p>
 * Author : Lcywings
 * <p>
 * Description : Redis配置类
 */
@Configuration
public class RedisConfig {

    /**
     * @author : Lcywings
     * @date : 2021/7/23 12:23
     * @acl : true
     * @description : 自定义Redis操作模板对象
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 创建一个Redis操作模板对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 两种序列化的方式
        // 借助String的序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // 借助fastJSON的序列化方式,方便存储对象
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        // 字符串类型的key和值序列化
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);

        // hash类型的key和值序列化
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

        // 初始化模板
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }


}